import {
  WgLayout,
  WgCell,
  compomentCreator,
  compomentDecode,
  compomentUpdate,
} from './design-com.js';

function getClsAttr() {
  return $('#emptyCls')[0].outerHTML.split(/\s+/)[1];
}

export class DesignDataStack {

  constructor(arg) {
    this.stack = [];
    this.pos = 0;
  }

  push = (data) => {
    this.stack.push(data);
    this.pos = this.stack.length - 1;
  }

  undo = () => {
    if (this.pos <= 0) {
      return;
    }
    this.pos -= 1;
    let data = this.stack[this.pos];
    webDesign.restore(data);
  }

  redo = () => {
    if (this.post >= this.stack.length - 1) {
      return;
    }
    this.pos += 1;
    let data = this.stack[this.pos];
    webDesign.restore(data);
  }

}


export class PropertySetting {

  constructor(arg) {
    this.selectedWg = null;
    this.vue = null;
  }

  selectWg = (wgId) => {
    let wg = $('#' + wgId);
    this.selectedWg = wg;
    let data = wg.data('com_data');
    data.action = data.action || {};
    data.action.property = data.action.property || {};
    data.action.service = data.action.service || {};

    if (data.name == 'switch') {
      data.action.switchOn = data.action.switchOn || {};
      data.action.switchOff = data.action.switchOff || {};
    }

    this.vue.wgData = data;
  }

  data = (wgEl, data) => {
    wgEl.data('com_data', data);
  }

  setVue = (vue) => {
    this.vue = vue;
  }

  update = (data) => {
    let updater = _compomentUpdate[data.name];
    if (updater) {
      updater(this.selectedWg, data);
      //暂存当前设计
      designDataStack.push(webDesign.serialize());
    }
  }

}

var movingAddCom;
var movingCom;
var isMoving = false;
var dropDistance = 0;
var startPos = {
  x: 0,
  y: 0
};
//属性设置
var propertySetting = new PropertySetting();
//根组件
var rootWiget = new WgLayout({
  colSize: 1
});

export class WebDesign {
  init = () => {
    $('.toolBox .compoment').on('mousedown', function(e) {
      movingAddCom = $(this).clone().addClass('moving')
      $(document.body).append(movingAddCom);
      movingAddCom.css('top', e.pageY).css('left', e.pageX);
      isMoving = true;
    });

    $('.pageContent').on('mousemove', function(e) {
      if (movingCom) {
        movingCom.css('top', e.pageY + 10 + 80).css('left', cX + e.pageX + 10 + 180);
      }
      if (movingAddCom) {
        movingAddCom.css('top', e.clientY + 10).css('left', e.clientX + 10);
      }
      return false;
    });

    let design = this;
    $('.pageContent').on('mouseup', '._container', function(e) {
      console.log('mouseup:', movingCom, 'isMoving:', isMoving)
      if (!isMoving) {
        return true;
      }
      let closestCom = $(this).closest('._compoment');
      if (movingAddCom) {
        //从组件库中拖放的
        movingAddCom.remove();

        let comName = movingAddCom.attr('com');
        let creator = _compomentCreator[comName];
        if (creator) {
          let wg = creator($(this), {
            props: {}
          });
        }
        movingAddCom = null;
        isMoving = false;
      } else if (movingCom) {
        //移动很小不处理
        let dx = Math.abs(startPos.x - e.pageX);
        let dy = Math.abs(startPos.y - e.pageY);
        console.log('dx:', dx, 'dy:', dy);
        if (dx < 20 && dy < 20) {
          isMoving = false;
          movingCom.remove();
          return false;
        }

        let com = movingCom.next();
        //不能添加到自己
        if (closestCom && closestCom.attr('id') == com.attr('id')) {
          isMoving = false;
          movingCom.remove();
          return false;
        }
        com.removeClass('_selected');

        //移动组件
        com.appendTo($(this));
        let groupIndex = com.index();
        movingCom.remove();
        movingCom = null;
        isMoving = false;
      }
      //暂存当前设计
      designDataStack.push(webDesign.serialize());
      return true;
    });

    $('.pageContent').on('mouseenter', '._compoment', function(e) {
      console.log('mouseenter', isMoving);
      if (isMoving) {
        return false;
      }
      if (!$(this).prev().is('._handler')) {
        webDesign.createHandler($(this));
      }
      return false;
    });

    $('.pageContent').on('click', '._compoment', function(e) {
      let handler = $(this).prev();
      $('._handler._selected').removeClass('_selected');
      if (handler.is('._handler')) {
        $('._handler').each(function() {
          if ($(this).attr('id') != handler.attr('id')) {
            $(this).next().removeClass('_selected');
            $(this).remove();
          }
        });
        handler.addClass('_selected');
        $(this).addClass('_selected');
      } else {
        webDesign.createHandler($(this), true);
      }

      //选中组件展示属性设置
      propertySetting.selectWg($(this).attr('id'));

      // webDesign.save();

      return false;
    });

    $('.pageContent').on('mousedown', '._compoment._selected', function(e) {
      isMoving = true;
      startPos = {
        x: e.pageX,
        y: e.pageY
      };
      movingCom = $(this).prev();
    });

    $('.pageContent').on('mouseleave', '._compoment', function(e) {
      console.log('mouseleave');
      let handler = $(this).prev();
      if (handler.is('._handler') && !handler.is('._selected')) {
        handler.remove();
      }
      return false;
    });

    $(document.body).keydown(function(e) {
      let com = $('._compoment._selected');
      //上38 下40 左37 右39换位置
      if (e.keyCode >= 37 && e.keyCode <= 40) {
        webDesign.exchangeCom(com, e.keyCode);
        return true;
      }

      //删除
      if (e.keyCode == 8) {
        if (com.length == 0) {
          return true;
        }
        let handler = com.prev();
        handler.remove();
        com.remove();
        //暂存当前设计
        designDataStack.push(webDesign.serialize());
      }
      return true;
    });

    $('.pageContent').click(function() {
      $('._handler').remove();
      $('._compoment._selected').removeClass('_selected');
    })
  }

  exchangeCom = (com, dir) => {
    let moveUp = (dir == 37 || dir == 38);
    let target;
    if (moveUp) {
      target = com.prev().prev();
    } else {
      target = com.next();
    }
    if (!target.is('._compoment')) {
      return true;
    }
    if (moveUp) {
      com.after(target);
    } else {
      com.prev().before(target);
    }
    rootWiget.exchange(com.attr('id'), target.attr('id'));
    //暂存当前设计
    designDataStack.push(webDesign.serialize());
  }

  createHandler = (com, selected) => {
    let clsAttr = getClsAttr();
    let data = this.getCompomentData(com);
    com.before($('<div ' + clsAttr + ' id="handler_' + (new Date().getTime()) +
      '" class="_handler ' + (com.is('._layout') ? '_block' : '') + (selected ? '_selected' : '') +
      '"><div ' + clsAttr + ' class="_title">' + data.desc +
      '</div></div>').css({
      width: com.outerWidth() + 4,
      height: com.outerHeight() + 4
    }));
  }

  serialize = () => {
    let rootCell = new WgCell({
      name: 'cell'
    });
    let root = new WgLayout({
      name: 'root',
      colSize: 1
    });
    root.add(rootCell);
    _compomentDecode.decodeChildren(rootCell, $('#rootWiget'))
    return root;
  }

  restore = (data) => {
    let root = $('#rootWiget');
    root.empty();
    data.children[0].children.forEach(child => {
      let creator = _compomentCreator[child.name];
      if (creator) {
        creator(root, child);
      }
    });
  }

  makeHtml = (wg) => {
    return '';
  }

  getCompomentData = (el) => {
    return el.data('com_data');
  }
}

var _compomentCreator = new compomentCreator();
var webDesign = new WebDesign();
var _compomentDecode = new compomentDecode();
var _compomentUpdate = new compomentUpdate();
var designDataStack = new DesignDataStack();

export {
  webDesign,
  propertySetting,
  designDataStack
};
